import os
from k8s.env import TEMPLATES_DIR, CONF_DIR, IMAGE_REPO
from conf.jinja2_tool import jinja2_dump
from kubernetes import client, config
from conf.yaml_tool import yaml_load, yaml_dump
from misc.color import INFO, SINFO, CRIT, SUMM, WARN


class StorageClassClient(object):
    def __init__(self):
        from log.logger import logger
        self.logger = logger
        self.ctx = client.StorageV1Api()

    def create(self):
        msg = "Namespace [None]: creating StorageClass [local-storage]"
        self.logger.info(msg)
        print(SINFO % ("|--Info: " + msg))

        body = {
            "kind": "StorageClass",
            "apiVersion": "storage.k8s.io/v1",
            "metadata": {
                "name": "local-storage"
            },
            "provisioner": "kubernetes.io/no-provisioner",
            "volumeBindingMode": "WaitForFirstConsumer",
        }
        try:
            resp = self.ctx.create_storage_class(body=body)
            msg = "Namespace [None]: StorageClass created, name=%s" % (resp.metadata.name)
            self.logger.info(msg)
            print(INFO % ("  |--Info: " + msg))
        except Exception as e:
            # conflict exception: 409
            if str(e).split()[0] != '(409)':
                msg = str(e)
                print(CRIT % ("  |--Error: " + msg))
            else:
                msg = "instance already exits."
                print(INFO % ("  |--Info: " + msg))
            self.logger.critical(msg)

    def update(self):
        pass